package com.zlzlib.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @DateTime: 2024/3/19 16:36
 * @Author zlz
 * @Version 1.0
 */
public class JacksonUtil {

    private static final ThreadLocal<ObjectMapper> OBJECT_MAPPER_THREAD_LOCAL =
            ThreadLocal.withInitial(ObjectMapper::new);

    public static ObjectMapper getInstance() {
        return OBJECT_MAPPER_THREAD_LOCAL.get();
    }

    public static String toJsonString(Object o) {
        try {
            return toJsonStringEp(o);
        } catch (JsonProcessingException e) {
            return "";
        }
    }

    public static String toJsonStringEp(Object o) throws JsonProcessingException {
        return getInstance().writeValueAsString(o);
    }

    public static <T> T toJson(String s, Class<T> tClass) throws JsonProcessingException {
        return getInstance().readValue(s, tClass);
    }

    public static <T> List<T> toJsonList(String s, Class<T> tClass) throws JsonProcessingException {
        JavaType javaType = getInstance().getTypeFactory().constructCollectionType(List.class, tClass);
        return getInstance().readValue(s, javaType);
    }

    public static <K, V> Map<K, V> toMapEp(String s) throws JsonProcessingException {
        return getInstance().readValue(s, new TypeReference<Map<K, V>>() {
        });
    }

    public static <K, V> Map<K, V> toMap(String s) {
        try {
            return toMapEp(s);
        } catch (JsonProcessingException e) {
            return new HashMap<>(0);
        }
    }
}
